<script setup>
import { ref, onMounted, nextTick } from "vue";
import {
  queryPageApi,
  queryDeptListApi,
  queryRoleListApi,
  getUserByIdApi,
  addUserApi,
  updateUserApi,
  deleteUserApi,
} from "@/api/user";
import { ElMessage, ElMessageBox } from "element-plus";
const token = ref("");
onMounted(() => {
  search();
  loadDeptList();
  loadRoleList();
  token.value = localStorage.getItem("token");
});

// 查询参数
const queryParams = ref({
  name: "",
  phone: "",
  deptId: "",
  status: "",
  page: 1,
  pageSize: 10,
});

// 表格数据
const userList = ref([]);
const total = ref(0);

// 部门列表
const deptList = ref([]);

// 角色列表
const roleList = ref([]);

// 加载部门列表
const loadDeptList = async () => {
  const result = await queryDeptListApi();
  if (result.code == 1) {
    deptList.value = result.data;
  }
};

// 加载角色列表
const loadRoleList = async () => {
  const result = await queryRoleListApi();
  if (result.code == 1) {
    roleList.value = result.data;
  }
};

// 搜索
const search = async () => {
  const result = await queryPageApi(queryParams.value);
  if (result.code == 1) {
    userList.value = result.data.rows;
    total.value = result.data.total;
  }
};

// 清空
const clear = () => {
  queryParams.value = {
    name: "",
    phone: "",
    deptId: "",
    status: "",
    page: 1,
    pageSize: 10,
  };
  search();
};

// 分页大小改变
const handleSizeChange = (val) => {
  search();
};

// 页码改变
const handleCurrentChange = (val) => {
  search();
};

// 对话框相关
const dialogFormVisible = ref(false);
const formTitle = ref("");
const formLabelWidth = "100px";
const userFormRef = ref(null);
const userTableRef = ref(null);

// 用户表单数据
const user = ref({
  id: undefined,
  username: "",
  name: "",
  phone: "",
  email: "",
  gender: "",
  status: "",
  deptId: "",
  roleId: "",
  image: "",
  remark: "",
});

// 表单校验规则
const rules = ref({
  username: [
    { required: true, message: "用户名为必填项", trigger: "blur" },
    { min: 3, max: 20, message: "用户名长度在3-20个字符", trigger: "blur" },
  ],

  name: [
    { required: true, message: "姓名为必填项", trigger: "blur" },
    { min: 2, max: 10, message: "姓名长度在2-10个字符", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "手机号为必填项", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "邮箱为必填项", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
  gender: [{ required: true, message: "性别为必填项", trigger: "change" }],
  status: [{ required: true, message: "状态为必填项", trigger: "change" }],
});

// 添加用户
const handleAdd = () => {
  dialogFormVisible.value = true;
  formTitle.value = "新增用户";
  user.value = {
    id: undefined,
    username: "",
    name: "",
    phone: "",
    email: "",
    gender: "",
    status: "",
    deptId: "",
    roleId: "",
    image: "",
    remark: "",
  };
  if (userFormRef.value) {
    userFormRef.value.resetFields();
  }
};

// 编辑用户
const handleEdit = async (id) => {
  const result = await getUserByIdApi(id);
  if (result.code == 1) {
    user.value = { ...result.data };
    formTitle.value = "修改用户";
    dialogFormVisible.value = true;
    await nextTick();
    if (userFormRef.value) {
      userFormRef.value.clearValidate();
    }
  } else {
    ElMessage.error(result.msg || "获取用户信息失败");
  }
};

// 保存用户
const save = async () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      const isUpdate = !!user.value.id;
      const result = isUpdate
        ? await updateUserApi(user.value)
        : await addUserApi(user.value);
      if (result.code == 1) {
        dialogFormVisible.value = false;
        ElMessage.success("保存成功");
        selectedUsers.value = [];
        if (userTableRef.value) {
          userTableRef.value.clearSelection();
        }
        search();
      } else {
        ElMessage.error(result.msg || "保存失败");
      }
    } else {
      ElMessage.error("请输入正确的数据");
    }
  });
};

// 删除用户
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm("您确认要删除该用户吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    const result = await deleteUserApi(id);
    if (result.code == 1) {
      ElMessage.success("删除成功");
      selectedUsers.value = [];
      if (userTableRef.value) {
        userTableRef.value.clearSelection();
      }
      search();
    } else {
      ElMessage.error(result.msg || "删除失败");
    }
  } catch (err) {
    // 用户取消删除
  }
};

// 选中的用户
const selectedUsers = ref([]);

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection;
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning("请选择要删除的用户");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );
    const ids = selectedUsers.value.map((item) => item.id).join(",");
    const result = await deleteUserApi(ids);
    if (result.code == 1) {
      ElMessage.success("批量删除成功");
      selectedUsers.value = [];
      if (userTableRef.value) {
        userTableRef.value.clearSelection();
      }
      search();
    } else {
      ElMessage.error(result.msg || "批量删除失败");
    }
  } catch (err) {
    // 用户取消删除
  }
};

// 文件上传相关
const uploadRef = ref(null);
const uploadLoading = ref(false);

// 上传成功处理
const handleAvatarSuccess = (response, file) => {
  console.log("上传成功:", response);
  if (response.code == 1) {
    user.value.image = response.data;
    ElMessage.success("头像上传成功");
  } else {
    ElMessage.error(response.msg || "头像上传失败");
  }
};

// 上传失败处理
const handleAvatarError = (error, file) => {
  console.error("上传失败:", error);
  ElMessage.error("头像上传失败");
};

// 上传前校验
const beforeAvatarUpload = (file) => {
  console.log("上传文件信息:", file);
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("上传头像图片只能是图片格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
    return false;
  }
  console.log("文件验证通过");
  return true;
};

// 移除头像
const handleAvatarRemove = () => {
  user.value.image = "";
};
</script>

<template>
  <div class="user-management">
    <!-- 搜索区域 -->
    <el-form
      :inline="true"
      :model="queryParams"
      ref="queryForm"
      class="search-form"
    >
      <el-form-item label="姓名">
        <el-input v-model="queryParams.name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="queryParams.phone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="部门">
        <el-select
          v-model="queryParams.deptId"
          placeholder="请选择"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="dept in deptList"
            :key="dept.id"
            :label="dept.name"
            :value="dept.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择"
          clearable
          style="width: 100%"
        >
          <el-option label="正常" :value="1" />
          <el-option label="停用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item class="search-buttons">
        <el-button type="primary" @click="search"
          ><el-icon><Search /></el-icon>搜索</el-button
        >
        <el-button @click="clear"
          ><el-icon><Refresh /></el-icon>清空</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="handleAdd"
        ><el-icon><Plus /></el-icon>添加用户</el-button
      >
      <el-button type="danger" @click="handleBatchDelete"
        ><el-icon><Delete /></el-icon>批量删除</el-button
      >
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="userList"
      style="width: 100%"
      border
      @selection-change="handleSelectionChange"
      ref="userTableRef"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="name" label="姓名" width="120" align="center" />
      <el-table-column
        prop="username"
        label="用户名"
        width="180"
        align="center"
      />
      <el-table-column label="头像" width="100" align="center">
        <template #default="scope">
          <el-avatar :size="40" :src="scope.row.image" :alt="scope.row.name" />
        </template>
      </el-table-column>
      <el-table-column
        prop="deptName"
        label="部门"
        width="180"
        align="center"
      />
      <el-table-column
        prop="roleName"
        label="角色"
        width="180"
        align="center"
      />
      <el-table-column prop="phone" label="手机号" width="160" align="center" />
      <el-table-column prop="status" label="状态" width="120" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? "正常" : "停用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="updateTime"
        label="最后操作时间"
        width="250"
        align="center"
      />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row.id)">
            <el-icon><Edit /></el-icon>修改
          </el-button>
          <el-button type="danger" link @click="handleDelete(scope.row.id)">
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 40, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/修改用户对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="formTitle" width="600px">
      <el-form
        :model="user"
        ref="userFormRef"
        :rules="rules"
        :label-width="formLabelWidth"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="user.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="user.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="user.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="user.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select
                v-model="user.gender"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option label="男" :value="1" />
                <el-option label="女" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="user.status"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option label="正常" :value="1" />
                <el-option label="停用" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门">
              <el-select
                v-model="user.deptId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="dept in deptList"
                  :key="dept.id"
                  :label="dept.name"
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色">
              <el-select
                v-model="user.roleId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="role in roleList"
                  :key="role.id"
                  :label="role.name"
                  :value="role.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="头像">
          <el-upload
            ref="uploadRef"
            class="avatar-uploader"
            :show-file-list="false"
            action="/api/upload"
            name="image"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
            :on-remove="handleAvatarRemove"
            accept=".png,.jpg,.jpeg"
            :loading="uploadLoading"
            :headers="{ token: token }"
          >
            <img v-if="user.image" :src="user.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip" style="margin-left: 20px">
            图片上传,支持扩展名: .png/.jpg/.jpeg 大小限制: 2M
          </div>
        </el-form-item>

        <el-form-item label="备注说明">
          <el-input
            v-model="user.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入用户的备注信息,最多200字"
            :maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.user-management {
  padding: 20px;
  background-color: #fff;
  min-height: 100%;
  border-radius: 8px;
}

.operation-area {
  margin: 20px 0;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.search-form :deep(.el-form-item) {
  margin-right: 15px;
  margin-bottom: 10px;
  min-width: 200px;
}

.search-buttons {
  margin-left: auto !important;
  min-width: auto !important;
  margin-bottom: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-button .el-icon) {
  margin-right: 4px;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  object-fit: cover;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 32px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
  text-align: center;
}
</style>
